#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sublime
import os
import functools
from . import LuaCommon
from .. import Common

def run():
	text = Common.getText()
	if text == '':
		return

	if LuaCommon.checkWorkState():
		return

	matchlist = []
	showlist = []

	for definitionsList in LuaCommon.getDefinitionsLists():
		for definition in definitionsList:
			for name in definition[0]:
				if name == text:
					matchlist.append(definition)
					showlist.append('%s    %s:%d' % (definition[1], os.path.basename(definition[2]), definition[3]))

	if len(matchlist) == 0:
		sublime.status_message('can\'t find definition \'%s\'' % text)
	elif len(matchlist) == 1:
		gotoDefinition(matchlist[0])
	else:
		sublime.active_window().show_quick_panel(showlist, functools.partial(onSelect, matchlist))

def onSelect(matchlist, index):
	if index < 0:
		return

	gotoDefinition(matchlist[index])

def gotoDefinition(definition):
	filepath = definition[2]
	if definition[4] == 1:
		filepath = os.path.join(LuaCommon.getQuickEnvPath(), filepath)
	
	if os.path.exists(filepath):
		sublime.active_window().open_file('%s:%d' % (filepath, definition[3]), sublime.ENCODED_POSITION)
	else:
		sublime.status_message('%s not exists' % filepath)
